package org.lzy.shop.activity

import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.lzy.shop.Constant
import org.lzy.shop.R
import org.lzy.shop.adapter.CommentAllAdapter
import org.lzy.shop.base.BaseMvvmActivity
import org.lzy.shop.databinding.ActivityCommentListBinding
import org.lzy.shop.response.ListDTO
import org.lzy.shop.viewmodel.CommentModel

/**
 * 商品评论列表
 */

class CommentListActivity : BaseMvvmActivity<ActivityCommentListBinding, CommentModel>({ ActivityCommentListBinding.inflate(it) }) {
    private val goodsID: String? by lazy { intent.extras?.getString(Constant.GOODID) }
    private var mPageIndex = 1
    private val commentAllAdapter: CommentAllAdapter by lazy { CommentAllAdapter() }
    private var isRefreshing = false
    private var isLoading = false
    private var hasMoreData = true


    override fun initView() {
        setTitleText(getResString(R.string.user_comment))
        binding.recyclerview.apply {
            layoutManager = LinearLayoutManager(this@CommentListActivity)
            layoutManager?.isItemPrefetchEnabled =true
            adapter = commentAllAdapter
        }
        binding.recyclerview.setItemViewCacheSize(20)
        binding.recyclerview.setHasFixedSize(true)

        binding.refreshLayout.setOnRefreshListener {
            refreshData()
        }


        // 设置RecyclerView滚动监听实现加载更多
        binding.recyclerview.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                val visibleItemCount = layoutManager.childCount
                val totalItemCount = layoutManager.itemCount
                val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()

                // 滚动到底部且有更多数据且不在加载中时触发加载更多
                if (visibleItemCount + firstVisibleItemPosition >= totalItemCount &&
                    firstVisibleItemPosition >= 0 &&
                    hasMoreData &&
                    !isLoading) {
                    loadMoreData()
                }
            }
        })
    }

    override fun initData() {
        observeCommentData()
    }

    override fun requestData() {
        getComment()
    }

    private fun observeCommentData() {
        mViewModel.getCommentData.observeWithLifecycle(this) {
            handleCommentResponse(it)
        }
    }

    //获取评论
    private fun getComment() {
        goodsID?.let { validGoodsId ->
            mViewModel.getComment(mPageIndex, validGoodsId)
        } ?: run {
            // 处理商品ID为空的情况
            showEmptyList()
        }
    }

    private fun handleCommentResponse(commentResponse: MutableList<ListDTO>?) {
        // 更新刷新状态
        if (isRefreshing) {
            binding.refreshLayout.isRefreshing = false
            isRefreshing = false
        }
        if (isLoading) {
            isLoading = false
        }

        when {
            commentResponse.isNullOrEmpty() -> {
                if (mPageIndex > 1) {
                    // 没有更多数据
                    hasMoreData = false
                } else {
                    showEmptyList()
                }
            }

            else -> {
                if (mPageIndex == 1) {
                    commentAllAdapter.submitList(commentResponse)
                } else {
                    commentAllAdapter.addAll(commentResponse)
                }
                // 如果返回的数据小于预期的一页数据量，可能没有更多数据了
                hasMoreData = commentResponse.size >= 10 // 假设每页10条数据，可根据实际情况调整
            }
        }
    }

    private fun showEmptyList() {
        commentAllAdapter.submitList(null)
        commentAllAdapter.stateView = showEmptyView()
    }

    // 刷新数据
    private fun refreshData() {
        if (!isRefreshing && !isLoading) {
            isRefreshing = true
            mPageIndex = 1
            getComment()
        }
    }

    // 加载更多数据
    private fun loadMoreData() {
        if (!isRefreshing && !isLoading && hasMoreData) {
            isLoading = true
            mPageIndex++
            getComment()
        }
    }

    override fun allClick() {}
}